package com.meiqiang.muxinnetty.service.impl;

import com.meiqiang.muxinnetty.mapper.UsersMapper;
import com.meiqiang.muxinnetty.pojo.Users;
import com.meiqiang.muxinnetty.service.UserService;
import com.meiqiang.muxinnetty.utils.FileUtil;
import com.meiqiang.muxinnetty.utils.FileUtils;
import com.meiqiang.muxinnetty.utils.QRCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper userMapper;


    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Override
    public boolean queryUsernameIsExist(String username) {
        Users user = new Users();
        user.setUsername(username);

        Users result = userMapper.selectOne(user);

        return result != null ? true : false;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String pwd) {

        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();

        criteria.andEqualTo("username", username);
        criteria.andEqualTo("password", pwd);

        Users result = userMapper.selectOneByExample(userExample);

        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users saveUser(Users user) {

        String userId = UUID.randomUUID().toString().replaceAll("-","");

        String basePath="/muxin";
        // 为每个用户生成一个唯一的二维码
        String qrCodePath = "/face/user" + userId + "qrcode.png";
        // muxin_qrcode:[username]
        qrCodeUtils.createQRCode(basePath+qrCodePath, "muxin_qrcode:" + user.getUsername());

        user.setQrcode(qrCodePath);
        user.setId(userId);
        userMapper.insert(user);

        return user;
    }

    @Override
    public Users updateUserInfo(Users user) {
        userMapper.updateByPrimaryKeySelective(user);
        return queryUserById(user.getId());
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    private Users queryUserById(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}
